<template>
  <doc-alert title="【交易】售后退款" url="https://doc.iocoder.cn/mall/trade-aftersale/" />

  <el-dialog v-model="dialogShow" :title="dialogTitle" width="1200px" append-to-body>
    <el-descriptions :column="3">
      <el-descriptions-item label="商品名称：">{{ form.productName || '--' }}</el-descriptions-item>
      <el-descriptions-item label="图片附件：" :span="2">
        <div class="media-container">
          <!-- 图片展示 -->
          <div v-for="(item, index) in imageList" :key="'img-' + index">
            <el-image
              :src="item.url"
              :preview-src-list="imageList.map((i) => i.url)"
              fit="cover"
              class="media-item"
            >
              <template #error>
                <div class="image-error">加载失败</div>
              </template>
            </el-image>
          </div>

          <!-- 视频展示 -->
          <div v-for="(item, index) in videoList" :key="'vid-' + index" class="video-wrapper">
            <video controls :poster="getVideoThumbnail(item)" class="media-item">
              <source :src="item.url" :type="'video/' + item.url.split('.').pop()" />
              您的浏览器不支持视频播放
            </video>
          </div>
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="用户名：">{{ form.userName || '--' }}</el-descriptions-item>
      <el-descriptions-item label="手机号：">{{ form.userPhone || '--' }}</el-descriptions-item>
      <el-descriptions-item label="地址：">{{ form.address || '--' }}</el-descriptions-item>
      <el-descriptions-item label="审核状态：" class-name="desc-item">
        <dict-tag :type="DICT_TYPE.SERVICE_RECORD_STATUS" :value="form.status" />
      </el-descriptions-item>
      <el-descriptions-item label="申请时间："
        >{{ formatDate(form.createTime) }}
      </el-descriptions-item>
      <el-descriptions-item label="驳回原因："
        >{{ form.contactPhonenumber || '--' }}
      </el-descriptions-item>
    </el-descriptions>

    <template #footer>
      <div class="dialog-footer flex justify-end">
        <div v-if="form.status === 0">
          <el-button type="primary" @click="handleAfterService('10')">受理</el-button>
          <el-button type="danger" @click="handleRejectService">不受理</el-button>
        </div>

        <el-button @click="dialogShow = false" class="ml-10px">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 驳回弹窗 -->
  <el-dialog v-model="rejectDialogShow" title="售后驳回" width="470px" append-to-body>
    <el-form ref="rejectFormRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="驳回原因" prop="remark">
        <el-input v-model="form.remark" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm('20')">确 定</el-button>
        <el-button @click="cancelDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 搜索 -->
  <ContentWrap>
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="68px">
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          class="!w-280px"
          clearable
          placeholder="请输入用户名"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="售后单号" prop="aftersalesOrderNo">
        <el-input
          v-model="queryParams.aftersalesOrderNo"
          class="!w-280px"
          clearable
          placeholder="请输入售后单号"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" class="!w-280px" clearable placeholder="请选择状态">
          <el-option label="全部" value=" " />
          <el-option
            v-for="dict in getDictOptions(DICT_TYPE.SERVICE_RECORD_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-280px"
          end-placeholder="自定义时间"
          start-placeholder="自定义时间"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-tabs v-model="queryParams.status" @tab-click="tabClick">
      <el-tab-pane
        v-for="item in statusTabs"
        :key="item.label"
        :label="item.label"
        :name="item.value"
      />
    </el-tabs>
    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column
        align="center"
        label="售后单号"
        min-width="200"
        prop="aftersalesOrderNo"
      />

      <el-table-column label="商品名称" min-width="180" prop="productName"/>

      <el-table-column align="center" label="用户名" prop="userName" min-width="100" />
      <el-table-column align="center" label="手机号" prop="userPhone" min-width="140" />
      <el-table-column align="center" label="地址"  prop="address" min-width="220" />
      <el-table-column align="center" label="申请时间" prop="createTime" min-width="180">
        <template #default="scope">
          <span>{{ formatDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="驳回原因" prop="remark" min-width="120" />
      <el-table-column align="center" label="状态" min-width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SERVICE_RECORD_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" min-width="174">
        <template #default="{ row }">
          <el-button link type="primary" icon="View" @click="handleDetails(row)"
            >查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
</template>
<script lang="ts" setup>
import * as afterSaleApiRecordApi from '@/api/mall/trade/afterSale/serviceRecord/index'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import { createImageViewer } from '@/components/ImageViewer'
import { TabsPaneContext } from 'element-plus'
import { cloneDeep } from 'lodash-es'

defineOptions({ name: 'TradeAfterSale' })
// 通过弹窗
const resolveDialogShow = ref(false)
// 审核通过
const handleResolve = (row) => {
  detailsInfo.value = row
  resolveDialogShow.value = true
}

// 处理媒体数据
const mediaList = computed(() => {
  if (!form.value.image) return [];
  return form.value.image.split(',').map(url => {
    const ext = url.split('.').pop().toLowerCase();
    return {
      url,
      type: ['png','jpg','jpeg','gif','webp'].includes(ext) ? 'image' : 'video'
    };
  });
});

// 分离图片和视频
const imageList = computed(() => mediaList.value.filter(m => m.type === 'image'));
const videoList = computed(() => mediaList.value.filter(m => m.type === 'video'));

// 获取视频缩略图
const getVideoThumbnail = (videoItem) => {
  // 这里简化处理，实际应使用视频第一帧或后端提供的缩略图
  return videoItem.url.replace('.mp4', '.jpg')
}
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<afterSaleApiRecordApi.TradeAfterSaleVO[]>([]) // 列表的数据
const statusTabs = ref([
  {
    label: '全部',
    value: ''
  }
])
const queryFormRef = ref() // 搜索的表单
// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  aftersalesOrderNo: null,
  userName: '',
  status: '0',
  createTime: []
})

const message = useMessage() // 消息弹窗

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = cloneDeep(queryParams)

    // 执行查询
    const res = await afterSaleApiRecordApi.getAfterSaleRecordPage(data)
    console.log('res..', res)
    list.value = res.list as afterSaleApiRecordApi.TradeAfterSaleVO[]
    total.value = res.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.pageNo = 1
  await getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** tab 切换 */
const tabClick = async (tab: TabsPaneContext) => {
  queryParams.status = tab.paneName
  await getList()
}

/** 处理售后服务 **/
const handleAfterService = async (type) => {
  await message.confirm(`您确定受理该订单吗？`)
  await handleAfterServiceApi(type)
  dialogShow.value = false
}

// 驳回弹窗
const rejectDialogShow = ref(false)
const rejectFormRef = ref()
// 驳回对象
const initForm = {
  aftersalesOrderNo: '',
  productName: '',
  skuId: '',
  content: '',
  image: '',
  video: '',
  address: '',
  userName: '',
  userPhone: '',
  status: '', //0-待处理  1-处理中  2-已处理 3-驳回
  remark: ''
}

const data = reactive<any>({
  form: { ...initForm },
  rules: {
    remark: [{ required: true, message: '驳回原因不能为空', trigger: 'blur' }]
  }
})
const { form, rules } = toRefs(data)

const recordId = ref()

/** 发起处理售后服务接口，type: 10:通过，20->status:2通过：驳回->status:3驳回， **/
const handleAfterServiceApi = async (type) => {
  const status = type === '10' ? 2 : 3
  await afterSaleApiRecordApi.handleAfterSale({
    id: form.value.id,
    status,
    remark: form.value.remark
  })
  message.success('操作成功！')
  await getList()
}

/** 处理驳回 **/
const handleRejectService = async () => {
  rejectDialogShow.value = true
  dialogShow.value = false
}

const submitForm = (type) => {
  rejectFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      await handleAfterServiceApi(type)
      rejectDialogShow.value = false
    }
  })
}
const cancelDialog = () => {
  rejectDialogShow.value = false
  rejectFormRef.value.resetFields()
}

/** 重置新增的表单以及其他数据  */
const reset = () => {
  form.value = { ...initForm }
  rejectFormRef.value?.resetFields()
}
const detailsInfo = ref({})
const dialogTitle = ref('')
const dialogShow = ref(false)
/** 查看详情 */
const handleDetails = async (row?: any) => {
  reset()
  detailsInfo.value = row
  const res = await afterSaleApiRecordApi.getAfterSaleRecordById(row.id)
  console.log('res..', res)
  Object.assign(form.value, res)
  dialogTitle.value = '服务记录信息'
  dialogShow.value = true
}

onMounted(async () => {
  await getList()
  // 设置 statuses 过滤
  for (const dict of getDictOptions(DICT_TYPE.SERVICE_RECORD_STATUS)) {
    statusTabs.value.push({
      label: dict.label,
      value: dict.value
    })
  }
})
</script>

<style lang="scss">
.media-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.media-item {
  width: 200px;
  height: 150px;
  border-radius: 4px;
  object-fit: cover;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.video-wrapper {
  position: relative;
}

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

</style>
